using Microsoft.EntityFrameworkCore;
using Terra.Core.Configuration;
using Terra.Core.Infrastructure.Security;
using Terra.Data.Context;
using Terra.Data.Models;

namespace Terra.IntegrationTests.Infrastructure;

/// <summary>
/// 集成测试基类
/// </summary>
public abstract class IntegrationTestBase : IDisposable
{
    protected readonly TerraDbContext Context;
    protected readonly ProjectSettings Settings;
    protected readonly ICurrentUser CurrentUser;
    protected readonly string DatabaseName;

    protected IntegrationTestBase()
    {
        // 使用时间戳创建唯一的数据库名
        var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
        DatabaseName = $"TerraTest_{timestamp}";

        Settings = new ProjectSettings
        {
            Name = "Terra",
            DisplayName = "Terra Platform",
            Company = "Terra",
            Version = "1.0.0",
            TablePrefix = "Terra_",
            CacheKeyPrefix = "Terra:",
            QueuePrefix = "Terra_"
        };

        CurrentUser = new TestCurrentUser();

        var options = new DbContextOptionsBuilder<TerraDbContext>()
            .UseSqlServer($"Server=localhost;Database={DatabaseName};Trusted_Connection=True;TrustServerCertificate=True;")
            .Options;

        Context = new TerraDbContext(options, Settings, CurrentUser);

        // 确保数据库存在并应用最新的迁移
        Context.Database.EnsureCreated();

        // 输出当前使用的数据库名称，方便查看
        Console.WriteLine($"测试数据库已创建: {DatabaseName}");
    }

    /// <summary>
    /// 设置审计信息
    /// </summary>
    /// <param name="entity">实体</param>
    protected void SetAuditInfo(BaseEntity entity)
    {
        if (entity == null) return;

        if (entity.Id == Guid.Empty)
        {
            entity.Id = Guid.NewGuid();
        }

        if (string.IsNullOrEmpty(entity.CreatedBy))
        {
            entity.CreatedBy = "TestUser";
            entity.CreatedTime = DateTime.UtcNow;
        }

        if (entity.IsDeleted && string.IsNullOrEmpty(entity.DeletedBy))
        {
            entity.DeletedBy = "TestUser";
            entity.DeletedTime = DateTime.UtcNow;
        }

        if (!entity.IsDeleted && entity.LastModifiedTime.HasValue && string.IsNullOrEmpty(entity.LastModifiedBy))
        {
            entity.LastModifiedBy = "TestUser";
        }
    }

    public void Dispose()
    {
        // 仅释放 Context，不删除数据库
        Context.Dispose();

        // 输出提示信息
        Console.WriteLine($"测试完成。您可以在数据库 {DatabaseName} 中查看测试数据。");
    }
}

/// <summary>
/// 测试用的当前用户服务实现
/// </summary>
public class TestCurrentUser : ICurrentUser
{
    public Guid? Id => Guid.Parse("00000000-0000-0000-0000-000000000001");
    public string Name => "TestUser";
    public bool IsAuthenticated => true;
}